/**
 * 角色信息数据列表页面JS
 * User: zhaoming
 * Date: 15-8-17
 * Time: 下午5:58
 * To change this template use File | Settings | File Templates.
 */
$(function(){
    //激活左侧导航菜单
    activeNavBar("AUTHORITY_ROLE_INFO", "AUTHORITY");
    //重置数据列表宽度
    $("#gridTableWidgetBody").resize(function(){
        $("#gridTable").setGridWidth($(this).width(), false);
    });
    //加载数据列表
    loadGrid();
    loadAssignResourceDialog();
    $("#query").click(function(){
        query();
    });
    $("#reset").click(function(){
        $('#searchForm')[0].reset();
        $('#searchForm').find('.form-select2').each(function(){
            if($(this).prop("disabled") != undefined && $(this).prop("disabled") != true){
                $(this).select2("val", "");
            }
        });
    });
    $("#insert").click(function(){
        openInsertPage();
    });
});

/**
 * 加载数据列表
 */
function loadGrid(){
    var gridTable = jQuery("#gridTable");
    gridTable.jqGrid({
        mtype: "POST",
        url: springUrl+"/web/roleInfo/pageQuery.json",
        datatype: "json",
        autowidth: true,
        height: "100%",
        colModel: [
            {name:'id', label:'ID', index:'id', width:50, sortable: false, resizable:false, hidden: true},
            {name:'roleCode',label:'角色编码', index:'role_code',width:100, sortable: false, align:'left'},
            {name:'roleName',label:'角色名称', index:'role_name', width:100, sortable: false, align:'left'},
            {name:'remark',label:'描述', index:'role_desc', width:200, sortable: false, align:'left'},
            {name:'createTime',label:'创建日期', index:'create_date', width:100, sortable: true, align:'center',
                formatter:function(cellValue,options,rowObject){
                    if(cellValue != null){
                        return new Date(cellValue).format("yyyy-MM-dd hh:mm:ss");
                    }else{
                        return "";
                    }
                }
            },
            {name:'', label:'操作', index:'', width:350, fixed:true, sortable:false, resize:false, align:'center',
                formatter:function(cellValue,options,rowObject){
                    var context = "";
                    context += '<button class="btn btn-white btn-info btn-bold" onclick="openAssignUsersPage('+rowObject.id+')"><i class="ace-icon fa fa-user bigger-120 blue"></i>分配用户</button> ';
                    context += '<button class="btn btn-white btn-info btn-bold" onclick="openAssignResourceWindow(\''+rowObject.roleCode+'\')"><i class="ace-icon fa fa-sitemap bigger-120 blue"></i>分配资源</button> ';
                    context += '<button class="btn btn-white btn-info btn-bold" onclick="openUpdatePage('+rowObject.id+')"><i class="ace-icon fa fa-pencil bigger-120 blue"></i>修改</button> ';
                    context += '<button class="btn btn-white btn-info btn-bold" onclick="deleteByPrimaryKey('+rowObject.id+')"><i class="ace-icon fa fa-trash-o bigger-120 blue"></i>删除</button>';
                    return context;
                }
            }
        ],
        rownumbers: true,//添加左侧行号
        viewrecords : true,
        rowNum: 10,
        rowList: [10,20,30],
        sortname: "create_time",
        sortorder: "desc",
        altRows: true,
        pager : "#gridPager",
        jsonReader: { //server返回Json解析设定
            root: "root", //对于json中数据列表
            page: "page",
            total: "total",
            records: "records"
        },
        loadComplete : function() {
            updatePagerIcons(this);
            $(this).setGridWidth($("#gridTableWidgetBody").width(), true);
        }
    });

    //navButtons
    gridTable.jqGrid('navGrid',"#gridPager",
        {
            add: false,
            addicon : 'icon-plus-sign purple',
            edit: false,
            editicon : 'icon-pencil blue',
            del: false,
            delicon : 'icon-trash red',
            view: false,
            viewicon : 'icon-zoom-in orange',
            search: false,
            searchicon : 'icon-search grey',
            refresh: false,
            refreshicon : 'icon-refresh green'
        }
    );
}

/**
 * 查询
 */
function query(){
    if($('#searchForm').trigger("validate").isValid()){

        var gridParam = {
            url: springUrl+"/web/roleInfo/pageQuery.json",
            postData:{
                roleCode : $("#roleCode").val(),
                roleName : $("#roleName").val()
            },
            page:1
        };
        $("#gridTable").jqGrid("setGridParam", gridParam).trigger("reloadGrid");
    }
}

/**
 * 打开新增页面
 */
function openInsertPage(){
    window.location.href = springUrl+"/web/roleInfo/insertPage";
}

/**
 * 打开分配用户窗口
 * @param roleCode 角色编码
 */
function openAssignUsersPage(id){
    var element = document.createElement("input");
    element.setAttribute("type", "hidden");
    element.setAttribute("id", "id");
    element.setAttribute("name", "id");
    element.setAttribute("value", id);

    var form = document.createElement("form");
    document.body.appendChild(form);
    form.method = 'post';
    form.action = springUrl+'/web/userRoleRelation/assignUserPage';
    form.appendChild(element);
    form.submit();
}

/**
 * 打开修改页面
 * @param id 主键ID
 */
function openUpdatePage(id){
    var element = document.createElement("input");
    element.setAttribute("type", "hidden");
    element.setAttribute("id", "id");
    element.setAttribute("name", "id");
    element.setAttribute("value", id);

    var form = document.createElement("form");
    document.body.appendChild(form);
    form.method = 'post';
    form.action = springUrl+'/web/roleInfo/updatePage';
    form.appendChild(element);
    form.submit();
}

/**
 * 根据主键删除数据
 * @param id 主键ID
 */
function deleteByPrimaryKey(id){
     Commons.showConfirm("是否删除该记录?", function(){
         jQuery.ajax({
             type: "POST",
             dataType: "json",
             url: springUrl+"/web/roleInfo/deleteByPrimaryKey",
             data: {
                 id:  id
             },
             success: function (data) {
                 Commons.showSuccess("数据删除成功!", function(){
                     $("#gridTable").trigger("reloadGrid");
                 });
             },
             error: function(data){
                 Commons.showError(data.responseText);
             }
         });
     })
}

/**
 * 初始化分配资源Dialog
 */
function loadAssignResourceDialog(){
    $("#roleResourceDialog").dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 600,
        height: 600,
        title_html: true,
        title: "<div class='widget-header'><h4 class='smaller'><i class='ace-icon fa fa-sitemap'></i><b> 分配资源</b></h4></div>",
        buttons: [
            {
                text: "保存",
                "class" : "button button-primary button-rounded button-default",
                click: function() {
                    assignResource();
                }
            },
            {
                text: "取消",
                "class" : "button button-action button-rounded button-default",
                click: function() {
                    $( this ).dialog( "close" );
                }
            }
        ]
    });
}

/**
 * 打开分配资源窗口
 * @param roleCode 角色编码
 */
function openAssignResourceWindow(roleCode){
    var zNodes =[];
    jQuery.ajax({
        type: "POST",
        dataType: "json",
        async: false,
        url: springUrl+"/web/roleResourceRelation/getResourceTree",
        data:{
            roleCode:  roleCode
        },
        success:function (data) {
            zNodes = data;
        },
        error : function(data){
            Commons.showError("打开分配资源窗口失败");
        }
    });

    var setting = {
        check: {
            enable: true,
            chkStyle: "checkbox",
            chkboxType: { "Y": "ps", "N": "ps" }
        },
        data: {
            simpleData: {
                enable: true
            }
        }
    };
    $.fn.zTree.init($("#resourceTree"), setting, zNodes);

    $("#waitAssignRoleCode").val(roleCode);
    $("#roleResourceDialog").dialog("open");
}

/**
 * 分配资源
 * @param roleCode 角色编码
 */
function assignResource(roleCode){
    var treeObj = $.fn.zTree.getZTreeObj("resourceTree");
    var nodes = treeObj.getCheckedNodes(true);
    var resources = "";
    for(var i=0;i<nodes.length;i++){
        resources = resources + nodes[i].code + ",";
    }

    jQuery.ajax({
        type: "POST",
        dataType: "json",
        url: springUrl+"/web/roleResourceRelation/insert",
        data:{
            roleCode:  $("#waitAssignRoleCode").val(),
            resources: resources
        },
        success:function (data) {
            $("#roleResourceDialog").dialog( "close" );
            Commons.showSuccess("数据保存成功!");
        },
        error : function(data){
            Commons.showError(data.responseText);
        }
    });
}

